import React from "react";
import { Carousel, Flex, Grid, WingBlank } from "antd-mobile";
// import axios from "axios";
import { BASE_URL } from '../../utils/url'
import { API } from '../../utils/api'
// 导入导航栏图片
import nav1 from "../../assets/images/nav-1.png";
import nav2 from "../../assets/images/nav-2.png";
import nav3 from "../../assets/images/nav-3.png";
import nav4 from "../../assets/images/nav-4.png";

// 导入Home组件样式
import "./index.css";
import SearchHeader from '../../components/SearchHeader'
// 导入 utils 获取当前定位城市的方法
import { getCurrentCity } from '../../utils'
// 导航菜单的数据
const navs = [
  {
    id: 0,
    img: nav1,
    title: "整租",
    path: "/layout/houselist",
  },
  {
    id: 1,
    img: nav2,
    title: "合租",
    path: "/layout/houselist",
  },
  {
    id: 2,
    img: nav3,
    title: "地图找房",
    path: "/map",
  },
  {
    id: 3,
    img: nav4,
    title: "去出租",
    path: "/rent/add",
  },
];
// console.log(navigator.geolocation.getCurrentPosition())
// 浏览器自带对象获取定位的方法
// navigator.geolocation.getCurrentPosition(function geo_success(position) {
//   console.log(position)
// },
// function error() {
//   alert("Sorry, no position available.");
//   })

export default class Home extends React.Component {
  state = {
    // 轮播图状态
    swipers: [],
    // 轮播图数据加载状态
    isSwiperLoading: false,
    // 租房小组状态
    groups: [],
    // 最新资讯
    news: [],
    // 当前定位城市名称
    currentCityName: '定位'
  };
  // 封装获取轮播图数据的方法
  async getSwipers() {
    const {
      data: { body },
    } = await API.get("/home/swiper");
    // console.log(body);
    this.setState(() => {
      return {
        swipers: body,
        isSwiperLoading: true,
      };
    });
  }
  // 封装获取租房小组数据的方法
  async getGroups() {
    let { data: res } = await API.get("/home/groups", {
      params: {
        area: "AREA%7C88cff55c-aaa4-e2e0",
      },
    });
    // 判断返回的状态是否是成功
    if (res.status !== 200) {
      console.error(res.description);
      return;
    }
    // 把获取到的值设置给state
    this.setState({
      groups: res.body,
    });
  }
  // 封装获取最新咨询的方法
  async getNews() {
    let { data: res } = await API.get(
      "/home/news?area=AREA%7C88cff55c-aaa4-e2e0"
    );
    // 判断返回的状态是否是成功
    if (res.status !== 200) {
      console.error(res.description);
      return;
    }
    // 把获取到的值设置给state
    this.setState({
      news: res.body,
    });
  }
  async componentDidMount() {
    this.getSwipers();
    this.getGroups();
    this.getNews();

    // 百度API 根据IP地址获取定位的方法
    const currentCity = await getCurrentCity()
    // console.log(currentCity);
      this.setState(() => {
        return {
          currentCityName: currentCity.label
        }
      } )
    // var myCity = new window.BMapGL.LocalCity()
    // myCity.get(async res => {
    //   // console.log(res)
    //   const result = await axios.get(`http://localhost:8080/area/info?name=${res.name}`)
    //   // console.log(result)
    //   this.setState(() => {
    //     return {
    //       currentCityName: result.data.body.label
    //     }
    //   } )
    // } )
  }
  // 封装重构导航栏菜单的方法
  mapFlexItem() {
    return navs.map((item) => (
      <Flex.Item
        key={item.id}
        onClick={() => {
          this.props.history.push(item.path);
        }}
      >
        <img src={item.img} alt="" />
        <h2>{item.title}</h2>
      </Flex.Item>
    ));
  }
  // 租房小组 自定义布局重构方法
  renderGroups(item) {
    return (
      <Flex className="group-item" justify="around">
        <div className="desc">
          <p className="title">{item.title}</p>
          <span className="info">{item.desc}</span>
        </div>
        <img src={BASE_URL + item.imgSrc} alt="" />
      </Flex>
    );
  }
  // 最新咨询 自定义布局重构方法
  renderNews() {
    return this.state.news.map((item) => {
      return (
        <div className="news-item" key={item.id}>
          <div className="imgwrap">
            <img
              className="img"
              src={ BASE_URL + item.imgSrc}
              alt=""
            />
          </div>
          <Flex className="content" direction="column" justify="between">
            <h3 className="title">{item.title}</h3>
            <Flex className="info" justify="between">
              <span>{item.from}</span>
              <span>{item.date}</span>
            </Flex>
          </Flex>
        </div>
      );
    });
  }
  render() {
    return (
      <div className="home-container">
        {/* 顶部导航结构 可以复用 */}
        <SearchHeader currentCityName={this.state.currentCityName}></SearchHeader>
        {/* 轮播图 */}
        {/* 用swiper-container包裹是为了解决 页面刷新后 网速慢情况下 轮播图出现前 导航栏菜单会掉下去的问题 */}
        <div className="swiper-container">
          {this.state.isSwiperLoading && (
            <Carousel autoplay={true} infinite>
              {this.state.swipers.map((val) => (
                <a
                  key={val}
                  href="http://www.baidu.com"
                  style={{
                    display: "inline-block",
                    width: "100%",
                    height: 212,
                  }}
                >
                  <img
                    src={BASE_URL + val.imgSrc}
                    alt=""
                    style={{ width: "100%", verticalAlign: "top" }}
                    // onLoad={() => { // 让轮播图自适应屏幕尺寸
                    //   // fire window resize event to change height
                    //   window.dispatchEvent(new Event('resize'));
                    //   this.setState({ imgHeight: 'auto' });
                    // }}
                  />
                </a>
              ))}
            </Carousel>
          )}
        </div>
        {/* 导航栏菜单 */}
        <Flex className="nav">{this.mapFlexItem()}</Flex>
        {/* 租房小组 */}
        <div className="group">
          <h3 className="group-title">
            租房小组 <span className="more">更多</span>
          </h3>
          <Grid
            data={this.state.groups}
            // {/* 列数 */}
            columnNum={2}
            // {/* 是否强制正方形 */}
            square={false}
            // {/* 是否有边框 */}
            hasLine={false}
            // {/* 自定义里面的布局 */}
            renderItem={(item) => this.renderGroups(item)}
          />
        </div>
        {/* 最新资讯 */}
        <div className="news">
          <h3 className="group-title">最新资讯</h3>
          <WingBlank size="md">{this.renderNews()}</WingBlank>
        </div>
      </div>
    );
  }
}
